package cn.tonyandmoney.voicenotes.notes.presenter.impl

import android.content.Context
import cn.tonyandmoney.baidu.asr.event.AsrResultEvent
import cn.tonyandmoney.baidu.asr.model.AsrFilterInvocation
import cn.tonyandmoney.baidu.bus.SpeechBus
import cn.tonyandmoney.voicenotes.notes.enums.OperationEnum
import cn.tonyandmoney.voicenotes.notes.filters.OperationFilter
import cn.tonyandmoney.voicenotes.notes.filters.SearchFilter
import cn.tonyandmoney.voicenotes.notes.presenter.IOperation
import com.dhh.rxlifecycle2.RxLifecycle
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info

/**
 * @author niantuo
 * @createdTime 2018/5/7 23:07
 *
 *
 */
open class SearchPresenter(mContext:Context,private val mSearchView:ISearchView) : IOperation, AnkoLogger {

    private val filterInvocation = AsrFilterInvocation()

    init {
        filterInvocation.addFilter(SearchFilter(this))
        filterInvocation.addFilter(OperationFilter(this))
        SpeechBus.register(AsrResultEvent::class.java)
                .compose<AsrResultEvent>(RxLifecycle.with(mContext).bindOnDestroy())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .subscribe({ onResultEvent(it) }, { it.printStackTrace() })
    }

    /**
     * 接收
     */
    private fun onResultEvent(event: AsrResultEvent) {
        val nluResult = event.nluResult
        if (event.code == AsrResultEvent.CODE_FINAL && nluResult.hasNluResult()) {
            info("onResultEvent->$nluResult")
            filterInvocation.doFilter(nluResult)
        }
    }

    override fun operation(operation: OperationEnum) {
        when (operation.code) {
            OperationEnum.CONFIRM.code -> mSearchView.confirm()
            OperationEnum.CANCEL.code -> mSearchView.cancel()
        }
    }

    /**
     * 搜索内容的会在这里
     * 实例：命令为：打开，查找，搜索 某某某
     */
    override fun operation(operation: OperationEnum, params: MutableMap<String, String>) {
        val keywords = params["all"] ?: ""
        info("关键词->$keywords")
        mSearchView.showSearch(keywords)
    }

    interface ISearchView{
        fun showSearch(keywords: String)

        fun confirm()

        fun cancel()
    }
}